<?php

/**
 * This is the model class for table "{{count_ad}}".
 *
 * The followings are the available columns in table '{{count_ad}}':
 * @property integer $CountID
 * @property string $Name
 * @property integer $Year
 * @property integer $Month
 * @property integer $Day
 * @property integer $View
 * @property integer $UserView
 * @property integer $TouristView
 * @property integer $Gview
 * @property integer $Ip
 * @property integer $Uv
 * @property integer $AddTime
 */
class CountAdModel extends BaseModel
{

	public static $db;
    public function getDbConnection(){
        if(self::$db!==null){
            return self::$db;
        }else{
            self::$db=Yii::app()->getComponent('db_count');
            if(self::$db instanceof CDbConnection)
                return self::$db;
            else
                throw new CDbException('连接出错');                    
        }            
    }

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{count_ad}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('CountID, AdMark, Year, Month, Day, View, UserView, TouristView, Gview, Ip, Uv, AddTime,RecordTime', 'safe'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'CountID' => '统计ID',
			'AdMark' => '广告标识',
			'Year' => '年',
			'Month' => '月',
			'Day' => '日',
			'View' => '访问次数',
			'UserView' => '会员访问次数',
			'TouristView' => '游客访问次数',
			'Gview' => '商品页访问次数',
			'Ip' => '独立IP数',
			'Uv' => 'UV数',
			'AddTime' => '添加时间',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('CountID',$this->CountID);
		$criteria->compare('AdMark',$this->AdMark,true);
		$criteria->compare('Year',$this->Year);
		$criteria->compare('Month',$this->Month);
		$criteria->compare('Day',$this->Day);
		$criteria->compare('View',$this->View);
		$criteria->compare('UserView',$this->UserView);
		$criteria->compare('TouristView',$this->TouristView);
		$criteria->compare('Gview',$this->Gview);
		$criteria->compare('Ip',$this->Ip);
		$criteria->compare('Uv',$this->Uv);
		$criteria->compare('AddTime',$this->AddTime);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	public function createSearchCriteria()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;


        if (isset($_GET['start_time']) && $_GET['start_time']) {
            $start_time = strtotime($_GET['start_time']);
            $criteria->addCondition("AddTime >= {$start_time}");
        }
        if (!empty($_GET['end_time'])) {
            $end_time = strtotime($_GET['end_time']) + 86399;
            $criteria->addCondition("AddTime < {$end_time}");
        }        


		$criteria->compare('CountID',$this->CountID);
		$criteria->compare('AdMark',$this->AdMark,true);
		$criteria->compare('Year',$this->Year);
		$criteria->compare('Month',$this->Month);
		$criteria->compare('Day',$this->Day);
		$criteria->compare('View',$this->View);
		$criteria->compare('UserView',$this->UserView);
		$criteria->compare('TouristView',$this->TouristView);
		$criteria->compare('Gview',$this->Gview);
		$criteria->compare('Ip',$this->Ip);
		$criteria->compare('Uv',$this->Uv);
		$criteria->compare('AddTime',$this->AddTime);

		return $criteria;
	}
	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return CountAdModel the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

    //数据保存前操作
    protected function beforeSave() {
        if ($this->isNewRecord) {
            $this->AddTime = TIME_TIME;
        }
        return true;
    }



    /**
     * 执行所选时间范围的统计，可能是某一天，可能是隔几天的分析，
     * 分析的时候是一天一天的时间去分析的
     * @param type $start_time 开始时间
     * @param type $end_time 结束时间
     * 每张GuestDataModel表表示每天的数据，给它做一下统计
     * @return boolean
     */
    public function sendFenxi($start_time = '', $end_time = '') {
        set_time_limit(400);
        if (empty($start_time)) {
            $start_time = strtotime(date('Y-m-d 00:00:00'));
        }
        if (empty($end_time)) {
            $end_time = strtotime(date('Y-m-d 23:59:59'));
        }

        //总共需要统计多少天的量
        $intCount = ($end_time - $start_time)%86400;
        for($i = 0; $i < $intCount; $i++){
            self::saveDataOneDate($start_time + $i*86400);
        }
    }



    /**
     * 通过一个时间戳或者时间然后判断是分析哪张表的数据，然后执行分析
     * @return [type] [description]
     */
    public static function saveDataOneDate($mixTime){
        if(is_numeric($mixTime)){
            //时间戳格式
        }else{
            //时间格式
            $mixTime = strtotime($mixTime);
        }
        $strTime = date('Ymd', $mixTime);
        //设置分析哪张GuestDataModel表。。。
        GuestDataModel::$strTableName = '{{guest_data'.$strTime.'}}';

        $arrAdList = AdModel::getListName();
        

        foreach ($arrAdList as $AdMark => $strName) {
        	$arrData = array();
        	$arrData['AdMark'] = $AdMark;
        	$arrData['Year'] = date('Y', $mixTime);
        	$arrData['Month'] = date('m', $mixTime);
        	$arrData['Day'] = date('d', $mixTime);
        	$arrData['RecordTime'] = strtotime($arrData['Year'].'-'.$arrData['Month'].'-'.$arrData['Day']);
        	$arrWhere = array('IsAd' => 1, 'AdMark' => $AdMark, 'Year' => $arrData['Year'], 'Month' => $arrData['Month'], 'Day' => $arrData['Day']);        	
        	//这一天总查看人数
        	$arrData['View'] = GuestDataModel::model()->count(BaseModel::getC($arrWhere));

        	//会员查看人数
        	$arrWhere['UserID'] = array('sign' => '>', 'data' => 0);
        	$arrData['UserView'] = GuestDataModel::model()->count(BaseModel::getC($arrWhere));

        	//游客访问人数
        	$arrData['TouristView'] = $arrData['View'] - $arrData['UserView'];

        	//商品访问人数
        	unset($arrWhere['UserID']);
        	$arrWhere['GoodsID'] = array('sign' => '>', 'data' => 0);
        	$arrData['Gview'] = GuestDataModel::model()->count(BaseModel::getC($arrWhere));


        	//独立IP
        	unset($arrWhere['GoodsID']);
        	$arrWhere['group'] = 'Ip';
        	$arrData['Ip'] = GuestDataModel::model()->count(BaseModel::getC($arrWhere));

        	//统计UV
        	$arrWhere['group'] = 'SessionID';
        	$arrData['Uv'] = GuestDataModel::model()->count(BaseModel::getC($arrWhere));

        	$objModel = self::model()->find(BaseModel::getC(array('AdMark' => $AdMark, 'Year' => $arrData['Year'], 'Month' => $arrData['Month'], 'Day' => $arrData['Day'])));
        	if(!$objModel){
        		$objModel = new CountAdModel();
        	}
        	$objModel->attributes = $arrData;
        	$objModel->save(false);
        	echo "广告标识{$AdMark}{$arrData['Month']}月{$arrData['Day']}分析完成</br>";
        }
        return true;         
    }



}
